<template>

    <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="70px" size="small">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="关键字">
                        <el-input v-model="queryDto.userName" style="width: 100%" placeholder="用户名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="创建时间">
                        <el-date-picker v-model="createTimes" type="daterange" range-separator="To"
                            start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchSysUser">
                    搜索
                </el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>

    <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click=" dialogVisible = true; addShow(); title = '添加表单'">添 加</el-button>
    </div>

    <!-- 添加弹窗和修改弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="40%">
        <el-form label-width="120px">
            <el-form-item label="用户名">
                <el-input v-model="sysUser.userName"/>
            </el-form-item>
            <el-form-item v-if="sysUser.id == null" label="密码">
                <el-input type="password" show-password v-model="sysUser.password" />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="sysUser.name" />
            </el-form-item>
            <el-form-item label="手机">
                <el-input v-model="sysUser.phone" />
            </el-form-item>
            <el-form-item label="头像">
                <el-upload class="avatar-uploader" action="http://localhost:8501/admin/system/fileUpload"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :headers="headers">
                    <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="描述">
                <el-input v-model="sysUser.description" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="title == '添加表单' ? submit() : updateUser()">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!---数据表格-->
    <el-table :data="list" style="width: 100%">
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="avatar" label="头像" #default="scope">
            <img :src="scope.row.avatar" width="50" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" #default="scope">
            {{ scope.row.status == 1 ? '正常' : '停用' }}
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" align="center" width="280" #default="scope">
            <el-button type="primary" size="small" @click="editSysUser(scope.row)">
                修改
            </el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row)">
                删除
            </el-button>
            <el-button type="warning" size="small" @click="showAssignRole(scope.row)">
                分配角色
            </el-button>
            <!-- 分配角色弹窗 -->
            <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
                <el-form label-width="80px">
                    <el-form-item label="用户名">
                        <el-input disabled :value="sysUser.userName"></el-input>
                    </el-form-item>

                    <el-form-item label="角色列表">
                        <el-checkbox-group v-model="userRoleIds">
                            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
                                {{ role.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="doAssiogn">提交</el-button>
                        <el-button @click="dialogRoleVisible = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
        :page-sizes="[10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
        layout="total, sizes, prev, pager, next" :total="total" />

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { DoAssignRoleToUser,GetSysRoleListByPage, saveSysUser, updateSysUser, deleteSysUser } from '@/api/sysUser'
import { GetAllRoleList} from '@/api/sysRole'
import { ElMessage, ElMessageBox } from 'element-plus'


/////////////////////////////////////////////用户列表功能
// 表格数据模型
const list = ref([]);

//控制添加和修改弹窗标题数据模型
const title = ref('')

// 分页条总记录数
const total = ref(0)

//分页数据
const pageParamsForm = {
    page: 1, // 当前页码
    limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm)

// 定义搜索表单数据模型,和后端queryDto类字段相同
const queryDto = ref({
    userName: "",
    createTimeBegin: "",
    createTimeEnd: ""
})
//定义搜索表单时间数据模型
const createTimes = ref([])

// onMounted钩子函数
onMounted(() => {
    fetchData()
})


//条件查询方法，异步请求
const fetchData = async () => {

    //获取开始和结束时间
    //长度等于2表示选择了开始和结束时间
    if (createTimes.value.length == 2) {
        //开始时间
        queryDto.value.createTimeBegin = createTimes.value[0]
        //结束时间
        queryDto.value.createTimeEnd = createTimes.value[1]
    }

    //传递参数顺序要一样
    const result = await GetSysRoleListByPage(pageParams.value.page, pageParams.value.limit, queryDto.value)
    console.log(queryDto.value);
    //列表数据
    list.value = result.data.list
    //总共有多少条数据
    total.value = result.data.total
}

//搜索方法
const searchSysUser = () => {
    fetchData()
}

//重置按钮点击事件处理函数
const resetData = () => {
    queryDto.value = {}
    createTimes.value = []
}


/////////////////////////////////////////////// 添加用户

//设置控制弹窗数据模型
const dialogVisible = ref(false)

// 定义提交表单数据模型
const defaultForm = {
    userName: "",
    name: "",
    phone: "",
    password: "",
    description: "",
    avatar: ""
}
const sysUser = ref(defaultForm)

//打开添加弹窗
const addShow = () => {
    sysUser.value = {}
}

//添加表单提交数据,异步请求
const submit = async () => {
    const result = await saveSysUser(sysUser.value);
    if (result.code === 200) {
        ElMessage.success('用户信息添加成功')
        dialogVisible.value = false
        fetchData()
    }

}

///////////////////////////////修改用户功能
//修改表单数据回显
const editSysUser = (row) => {
    //打开编辑表单
    dialogVisible.value = true
    //修改编辑表单标题
    title.value = '编辑表单'
    //数据回显
    sysUser.value = { ...row }
}

//修改功能，异步请求
const updateUser = async () => {
    //调用接口
    const result = await updateSysUser(sysUser.value);
    if (result.code === 200) {
        ElMessage.success('用户信息修改成功')
        //关闭弹窗
        dialogVisible.value = false
        fetchData()
    }
}

////////////////////////////删除用户功能

const deleteUser = async (row) => {

    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const { code } = await deleteSysUser(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            //设置当前页为第一页
            pageParams.value.page = 1
            //刷新列表
            fetchData()
        }
    })


}
/////////////////////////////////////////////////minio文件上传
import { useApp } from '@/pinia/modules/app'

const headers = {
    token: useApp().authorization.token     // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
    //文件路径
    sysUser.value.avatar = response.data
}

//////////////////////////////////////////////////////////用户分配角色
// 角色列表
const userRoleIds = ref([])
const allRoles = ref([
    {"id":1 , "roleName":"管理员"},
    {"id":2 , "roleName":"业务人员"},
    {"id":3 , "roleName":"商品录入员"},
])
//控制分配角色弹窗
const dialogRoleVisible = ref(false)

//显示分配角色弹窗
const showAssignRole = async (row) => {

    //数据回显
    sysUser.value = {...row}

    //显示弹窗
    dialogRoleVisible.value = true

    //调用接口，异步请求
    const result = await GetAllRoleList(row.id) ;
    
    //数据回显，所有的角色  allRolesList 要和后端传来的数据要一样
    allRoles.value = result.data.allRolesList

    //数据回显，用户分配过的角色, sysUserRoles 要和后端传来的数据要一样
    userRoleIds.value = result.data.sysUserRoles

}

//分配角色，异步请求
const doAssiogn = async()=>{
    let assginRoleVo = {
        //key : 必须和后端封装的实体一致
        userId:sysUser.value.id,
        roleIdList:userRoleIds.value
    }
    const result = await DoAssignRoleToUser(assginRoleVo)
    if(result.code === 200){
        ElMessage.success('操作成功')
        // 关闭弹窗
        dialogRoleVisible.value = false
        // 刷新列表
        fetchData()
    }
}


</script>



<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>